<template>
  <div v-if="hasData" class="w-screen h-screen overflow-hidden flex flex-col">
    <TopBar
      :title="problem.title"
      @back="goBack"
      @debug="handleDebugSql"
      @run="handleRunSql"
    />
    <div class="flex-1 overflow-hidden bg-gray-100 px-2 min-h-0">
      <a-spin :spinning="loading" class="h-full">
        <split-pane
          direction="horizontal"
          :default-ratio="40"
          :min-size="40"
          :current-ratio="splitRatio"
          @update:ratio="handleRatioChange"
        >
          <template #first>
            <sql-content
              v-model="activeTab"
              :tabs="tabs"
              :is-collapsed="isCollapsed"
              :is-min-width="isMinWidth"
              :is-liked="problem.isLiked"
              :is-starred="problem.isStarred"
              :stats="{
                thumbNum: problem.thumbNum,
                commentCount: problem.commentCount,
                favourNum: problem.favourNum,
              }"
              @collapse="collapsePanel"
              @expand="expandPanel"
              @like="handleLike"
              @comment="handleComment"
              @star="handleStar"
            >
              <template #default="{ activeTab }">
                <div v-if="activeTab === 'description'" class="p-4">
                  <problem-description
                    ref="descriptionRef"
                    :problem="problem"
                    :is-discussion-expanded="isDiscussionExpanded"
                  />
                </div>
                <div v-else-if="activeTab === 'solution'" class="p-4">
                  <a-spin :spinning="solutionLoading">
                    <div
                      v-if="solution"
                      class="bg-white rounded-lg p-4 shadow-sm"
                    >
                      <!-- 作者信息区域 -->
                      <div
                        class="flex items-center justify-between mb-6 pb-4 border-b border-gray-200"
                      >
                        <div class="flex items-center">
                          <a-avatar
                            :src="solution.avatarUrl"
                            :size="48"
                            class="mr-4"
                          />
                          <div>
                            <div class="text-lg font-semibold text-gray-900">
                              {{ solution.nickName }}
                            </div>
                            <div class="text-sm text-gray-500">
                              {{ solution.topicName }}
                            </div>
                          </div>
                        </div>
                      </div>

                      <!-- 题解内容 -->
                      <div class="prose max-w-none">
                        <div
                          v-for="(part, index) in formattedExplain"
                          :key="index"
                        >
                          <div
                            v-if="part.type === 'text'"
                            class="text-gray-700 leading-relaxed mb-2"
                          >
                            {{ part.content }}
                          </div>
                          <div
                            v-else-if="part.type === 'code'"
                            class="relative"
                          >
                            <pre
                              class="bg-gray-50 rounded-lg font-mono px-2 text-sm overflow-x-auto"
                            >
                              <code class="block text-gray-800 px-4 leading-6">{{ part.content }}</code>
                            </pre>
                            <a-button
                              type="link"
                              class="absolute top-1 right-2 text-gray-400 hover:text-blue-500"
                              @click="copyCode(part.content)"
                            >
                              <CopyOutlined />
                            </a-button>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div
                      v-else-if="!solutionLoading"
                      class="text-center text-gray-500 py-8"
                    >
                      暂无题解
                    </div>
                  </a-spin>
                </div>
                <div v-else-if="activeTab === 'history'" class="p-2">
                  <SubmissionHistory
                    :submissions="mockSubmissions"
                    :loading="loading"
                  />
                </div>
                <div v-if="activeTab === 'testcase'" class="h-full">
                  <TestCasePanel :test-cases="testCases" />
                </div>
              </template>
            </sql-content>
          </template>

          <template #second>
            <split-pane
              direction="vertical"
              :default-ratio="70"
              :min-size="40"
              :current-ratio="verticalSplitRatio"
              @update:ratio="handleVerticalRatioChange"
            >
              <template #first>
                <sql-editor
                  v-model:value="editorValue"
                  :is-collapsed="isVerticalCollapsed"
                  @collapse="collapseVerticalPanel"
                  @expand="expandVerticalPanel"
                >
                  <div class="h-full w-full">
                    <textarea
                      v-model="editorValue"
                      class="w-full h-full p-4 resize-none border-none outline-none"
                    ></textarea>
                  </div>
                </sql-editor>
              </template>
              <template #second>
                <sql-result-panel
                  :is-collapsed="isBottomCollapsed"
                  v-model="bottomActiveTab"
                  :tabs="resultTabs"
                  @collapse="collapseBottomPanel"
                  @expand="expandBottomPanel"
                >
                  <template #default="{ activeTab }">
                    <div class="h-full">
                      <div v-if="activeTab === 'testcase'" class="h-full">
                        <TestCasePanel :test-cases="testCases" />
                      </div>
                      <div v-else-if="activeTab === 'result'" class="h-full">
                        <TestResultPanel :results="testResult" />
                      </div>
                      <div v-else-if="activeTab === 'run'" class="h-full">
                        <RunResultPanel :results="runResult" />
                      </div>
                    </div>
                  </template>
                </sql-result-panel>
              </template>
            </split-pane>
          </template>
        </split-pane>
      </a-spin>
    </div>
  </div>
  <div
    v-else-if="!loading"
    class="w-full h-full flex items-center justify-center"
  >
    <span class="text-gray-500">暂无数据</span>
  </div>
</template>

<script setup>
import SqlContent from "../../../components/SqlContent.vue";
import SqlEditor from "../../../components/SqlEditor.vue";
import TopBar from "../../../components/TopBar.vue";
import { ref, computed, nextTick, watch, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { topic } from "../../../api/frontend/topic";
import {
  ReadOutlined,
  SolutionOutlined,
  HistoryOutlined,
  ExperimentOutlined,
  CheckSquareOutlined,
  CommentOutlined,
  CaretRightOutlined,
  CopyOutlined,
} from "@ant-design/icons-vue";
import { Spin, message } from "ant-design-vue";
import SplitPane from "../../../components/SplitPane.vue";
import SqlResultPanel from "../../../components/SqlResultPanel.vue";
import ProblemDescription from "../../../components/problem/ProblemDescription.vue";
import SubmissionHistory from "../../../components/problem/SubmissionHistory.vue";
import TestCasePanel from "../../../components/problem/TestCasePanel.vue";
import TestResultPanel from "../../../components/problem/TestResultPanel.vue";
import RunResultPanel from "../../../components/problem/RunResultPanel.vue";

const loading = ref(true);
const route = useRoute();
const problem = ref({});

// 移除原来的静态 testCases 数据，改为响应式引用
const testCases = ref([]);

// 移除原来的静态 testResult 数据，改为响应式引用
const testResult = ref([]);

// 添加运行结果数据
const runResult = ref([]);

// 修改获取题目详情的处理逻辑
const fetchProblemDetail = async () => {
  try {
    loading.value = true;
    const response = await topic.getTopicDetail(route.params.id);

    console.log(response, "题目详情"); // 添加调试日志
    if (response.code === 200 && response.data) {
      const apiData = response.data;

      // 处理测试用例数据，包含输入和期望输出
      testCases.value = apiData.testTopicList || [];

      // 处理测试结果数据
      testResult.value =
        apiData.testTopicList?.map((testTopic) => ({
          status: "待执行",
          executionTime: 0,
          testCase: testTopic.inputList?.map((input) => ({
            name: input.tableName,
            columns: Object.keys(input.data[0] || {}),
            data: input.data,
          })),
          output: {
            headers: testTopic.outputList?.[0]?.columns || [],
            rows: testTopic.outputList?.[0]?.data || [],
          },
        })) || [];

      // 转换数据结构
      const transformedData = {
        id: apiData.id,
        title: apiData.title || "SQL题目",
        difficulty: apiData.difficulty,
        description: apiData.content || "",
        tables:
          apiData.topicTableList?.map((table) => ({
            name: table.name,
            description: table.description,
            columns: table.columnList?.map((col) => ({
              name: col.name,
              type: col.type,
              description: col.description,
            })),
          })) || [],
        examples:
          apiData.testTopicList?.length > 0
            ? [
                {
                  // 只取第一条测试用例
                  input: apiData.testTopicList[0].inputList?.reduce(
                    (acc, input) => {
                      acc[input.tableName] = input.data;
                      return acc;
                    },
                    {}
                  ),
                  output: apiData.testTopicList[0].outputList || [],
                },
              ]
            : [],
        passCount: apiData.passNum || 0,
        submitCount: apiData.submitNum || 0,
        isLiked: apiData.isThumb || false,
        isStarred: apiData.isFavour || false,
        thumbNum: parseInt(apiData.thumbNum) || 0,
        favourNum: parseInt(apiData.favourNum) || 0,
        commentCount: 0,
        tags: apiData.tagList || [],
        hints: [],
      };

      console.log("处理后的数据:", transformedData); // 添加调试日志
      problem.value = transformedData;
    } else {
      console.error("API响应异常:", response);
    }
  } catch (error) {
    console.error("获取题目详情失败:", error);
  } finally {
    loading.value = false;
  }
};

// 在组件挂载时获取题目详情
onMounted(() => {
  fetchProblemDetail();
});

const router = useRouter();
const goBack = () => router.back();

// 左侧内容面板相关
const activeTab = ref("description");
const tabs = [
  { key: "description", label: "题目描述", icon: ReadOutlined },
  { key: "solution", label: "题解", icon: SolutionOutlined },
  { key: "history", label: "答题记录", icon: HistoryOutlined },
];

// 面板宽度检测
const isMinWidth = computed(
  () =>
    document.querySelector(".split-pane > div:first-child")?.offsetWidth <= 80
);

// 左侧面板折叠控制
const initialRatio = 40;
const splitRatio = ref(initialRatio);
const isCollapsed = computed(() => splitRatio.value <= 5);

const handleRatioChange = (ratio) => (splitRatio.value = ratio);
const expandPanel = () => (splitRatio.value = initialRatio);
const collapsePanel = () => {
  const containerWidth =
    document.querySelector(".split-pane")?.offsetWidth || 1000;
  splitRatio.value = (42 / containerWidth) * 100; // 修改为42px
};

// 垂直分割相关
const initialVerticalRatio = 70;
const verticalSplitRatio = ref(initialVerticalRatio);
const isVerticalCollapsed = computed(() => verticalSplitRatio.value <= 10);
const isBottomCollapsed = computed(() => 100 - verticalSplitRatio.value <= 10);

const handleVerticalRatioChange = (ratio) => (verticalSplitRatio.value = ratio);

// 面板展开/收起处理函数
const expandVerticalPanel = () =>
  (verticalSplitRatio.value = initialVerticalRatio);
const collapseVerticalPanel = () => {
  const containerHeight =
    document.querySelector(".split-pane .split-pane")?.offsetHeight || 1000;
  verticalSplitRatio.value = (42 / containerHeight) * 100; // 修改为42px
};

const expandBottomPanel = () =>
  (verticalSplitRatio.value = 100 - initialBottomRatio);
const collapseBottomPanel = () => {
  const containerHeight =
    document.querySelector(".split-pane .split-pane")?.offsetHeight || 1000;
  verticalSplitRatio.value = 100 - (42 / containerHeight) * 100; // 修改为42px
};

// 结果区域配置
const initialBottomRatio = 30;
const bottomActiveTab = ref("testcase"); // 确保这个值与 tabs 中的 key 对应
const resultTabs = [
  { key: "testcase", label: "测试用例", icon: ExperimentOutlined },
  { key: "result", label: "测试结果", icon: CheckSquareOutlined },
  { key: "run", label: "提交结果", icon: CaretRightOutlined }, // 添加运行结果标签页
];

// 添加一个监听器来处理标签切换
watch(bottomActiveTab, (newVal) => {
  console.log("切换到:", newVal); // 用于调试
});

// 编辑器值
const editorValue = ref("-- 在这里编写你的SQL查询\nSELECT * FROM dreams;");

// 修改点赞处理函数
const handleLike = async () => {
  try {
    const result = await topic.thumbTopic(problem.value.id);
    if (result.code === 200) {
      problem.value.isLiked = !problem.value.isLiked;
      problem.value.thumbNum += problem.value.isLiked ? 1 : -1;
      message.success(problem.value.isLiked ? "点赞成功" : "取消点赞成功");
    }
  } catch (error) {
    console.error("点赞失败:", error);
    message.error("操作失败，请稍后重试");
  }
};

// 添加展开讨论区的状态
const isDiscussionExpanded = ref(false);

// 修改评论按钮点击处理函数
const handleComment = async () => {
  const descriptionEl = descriptionRef.value?.$el;

  // 如果讨论区已展开，则关闭
  if (isDiscussionExpanded.value) {
    isDiscussionExpanded.value = false;
    return;
  }

  // 如果不在描述页面，先切换到描述页面
  if (activeTab.value !== "description") {
    activeTab.value = "description";
    await nextTick();
  }

  // 展开讨论区
  isDiscussionExpanded.value = true;

  // 等待DOM更新后滚动到讨论区
  await nextTick();
  const discussionEl = descriptionEl?.querySelector(".discussion-section");
  if (discussionEl) {
    discussionEl.scrollIntoView({ behavior: "smooth" });
  }
};

// 修改收藏处理函数
const handleStar = async () => {
  try {
    const result = await topic.favourTopic(problem.value.id);
    if (result.code === 200) {
      problem.value.isStarred = !problem.value.isStarred;
      problem.value.starCount += problem.value.isStarred ? 1 : -1;
      message.success(problem.value.isStarred ? "收藏成功" : "取消收藏成功");
    }
  } catch (error) {
    console.error("收藏失败:", error);
    message.error("操作失败，请稍后重试");
  }
};

// 添加滚动到讨论区的方法
const descriptionRef = ref(null);

// 修改提交记录相关的代码
const mockSubmissions = ref([]);

// 添加获取提交记录的方法
const fetchSubmissionHistory = async () => {
  try {
    const response = await topic.getSubmitLogs(route.params.id);
    if (response.code === 200) {
      mockSubmissions.value = response.data.data.map((item) => ({
        id: item.id,
        status: item.status === 1 ? "执行通过" : "执行失败",
        executionTime: parseInt(item.time),
        language: item.type,
        submitTime: item.createTime,
        sql: item.submitSql,
        createTime: item.createTime,
      }));
    }
  } catch (error) {
    console.error("获取提交记录失败:", error);
    message.error("获取提交记录失败");
  }
};

// 监听标签页切换，当切换到 history 时加载数据
watch(activeTab, (newTab) => {
  if (newTab === "history") {
    fetchSubmissionHistory();
  }
});

// 添加防止空数据渲染的计算属性
const hasData = computed(() => {
  return problem.value && Object.keys(problem.value).length > 0;
});

// 修改调试SQL的处理函数
const handleDebugSql = async () => {
  try {
    // 切换到测试结果面板
    bottomActiveTab.value = "result";

    // 确保底部面板展开
    if (isBottomCollapsed.value) {
      verticalSplitRatio.value = 70;
    }

    // 设置加载状态
    testResult.value = [
      {
        message: "执行中...",
        time: 0,
        status: "执行中",
        result: [],
        expectedResult: [],
        passed: false,
        error: null,
        loading: true,
      },
    ];

    // 调用测试接口
    const response = await topic.testTopic({
      id: problem.value.id,
      sql: editorValue.value,
    });

    if (response.code === 400) {
      // 直接显示错误信息
      testResult.value = [
        {
          error: response.data || response.msg,
          time: 0,
          status: "失败",
          result: [],
          expectedResult: [],
          passed: false,
          loading: false,
        },
      ];
      return;
    }

    if (response.code === 200) {
      testResult.value = response.data.map((item) => ({
        ...item,
        loading: false,
      }));
    } else {
      testResult.value = [
        {
          error: response.msg || "执行失败",
          time: 0,
          status: "失败",
          result: [],
          expectedResult: [],
          passed: false,
          loading: false,
        },
      ];
    }
  } catch (error) {
    console.error("SQL测试失败:", error);
    testResult.value = [
      {
        error: error.message || "测试执行失败，请稍后重试",
        time: 0,
        status: "失败",
        result: [],
        expectedResult: [],
        passed: false,
        loading: false,
      },
    ];
  }
};

// 修改运行处理函数
const handleRunSql = async () => {
  try {
    // 切换到运行结果面板
    bottomActiveTab.value = "run";

    // 确保底部面板展开
    if (isBottomCollapsed.value) {
      verticalSplitRatio.value = 70;
    }

    // 设置加载状态
    runResult.value = [
      {
        message: "执行中...",
        time: 0,
        status: "执行中",
        result: [],
        expectedResult: [],
        passed: false,
        error: null,
        loading: true,
      },
    ];

    // 调用运行接口
    const response = await topic.runTopic({
      id: problem.value.id,
      sql: editorValue.value,
    });

    if (response.code === 400) {
      runResult.value = [
        {
          error: response.data || response.msg,
          time: 0,
          status: "失败",
          result: [],
          expectedResult: [],
          passed: false,
          loading: false,
        },
      ];
      // 即使执行失败也刷新提交记录
      await fetchSubmissionHistory();
      return;
    }

    if (response.code === 200) {
      runResult.value = response.data.map((item) => ({
        ...item,
        loading: false,
      }));
    } else {
      runResult.value = [
        {
          error: response.msg || "执行失败",
          time: 0,
          status: "失败",
          result: [],
          expectedResult: [],
          passed: false,
          loading: false,
        },
      ];
    }
    
    // 无论成功失败都刷新提交记录
    await fetchSubmissionHistory();
  } catch (error) {
    console.error("SQL运行失败:", error);
    runResult.value = [
      {
        error: error.message || "运行失败，请稍后重试",
        time: 0,
        status: "失败",
        result: [],
        expectedResult: [],
        passed: false,
        loading: false,
      },
    ];
    // 发生错误时也刷新提交记录
    await fetchSubmissionHistory();
  }
};

// 添加题解相关数据和方法
const solution = ref(null);
const solutionLoading = ref(false);

// 添加获取题解的方法
const loadSolution = async () => {
  try {
    if (!route.params.id) return;

    solutionLoading.value = true;
    const response = await topic.getExplain(route.params.id);
    console.log("题解数据:", response); // 添加调试日志

    if (response.code === 200) {
      solution.value = response.data;
    } else {
      message.error("获取题解失败");
    }
  } catch (error) {
    console.error("获取题解失败:", error);
    message.error("获取题解失败");
  } finally {
    solutionLoading.value = false;
  }
};

// 在组件挂载时和切换到solution标签时都加载题解
onMounted(() => {
  if (activeTab.value === "solution") {
    loadSolution();
  }
});

watch(activeTab, (newVal) => {
  if (newVal === "solution") {
    loadSolution();
  }
});

// 添加格式化题解内容的计算属性
const formattedExplain = computed(() => {
  if (!solution.value?.explain) return [];
  return solution.value.explain
    .split(/(`[^`]+`)/)
    .map((text) => {
      if (text.startsWith("`") && text.endsWith("`")) {
        return {
          type: "code",
          content: text.slice(1, -1).trim(),
        };
      }
      return {
        type: "text",
        content: text,
      };
    })
    .filter((part) => part.content);
});

// 添加复制代码的方法
const copyCode = async (code) => {
  try {
    await navigator.clipboard.writeText(code);
    message.success("SQL已复制到剪贴板");
  } catch (err) {
    // 降级处理
    const textarea = document.createElement("textarea");
    textarea.value = code;
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand("copy");
    document.body.removeChild(textarea);
    message.success("SQL已复制到剪贴板");
  }
};
</script>

<style scoped>
/* 只保留必要的样式 */
:deep(.ant-btn) {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

:deep(.ant-btn:hover) {
  color: rgba(0, 0, 0, 0.88) !important;
  border-color: transparent !重要;
}

:deep(.ant-btn.text-gray-400:hover) {
  color: rgb(75, 85, 99) !important;
  background-color: rgb(243, 244, 246);
}

:deep(.ant-btn.text-gray-900:hover) {
  color: rgb(17, 24, 39) !important;
  background-color: rgb(243, 244, 246);
}

/* 移除可能影响布局的样式 */
.transition-all {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

/* 添加代码块相关样式 */
pre {
  margin: 0;
  line-height: 1.4;
}

code {
  white-space: pre-wrap;
  word-break: break-all;
}
</style>
